<template>
  <div
    class="message-item"
    :class="{
      'message-user': message.role === 'user',
      'message-assistant': message.role === 'assistant'
    }"
  >
    <div class="message-avatar">
      <el-avatar
        v-if="message.role === 'user'"
        :size="32"
        :icon="User"
      />
      <el-avatar
        v-else
        :size="32"
        :icon="ChatDotRound"
        :style="{ backgroundColor: 'var(--el-color-primary)' }"
      />
    </div>

    <div class="message-content-wrapper">
      <div class="message-content">
        <!-- 按时间顺序显示 items（工具调用和文本块） -->
        <template v-if="message.items && message.items.length > 0">
          <div
            v-for="item in message.items"
            :key="item.id || item.type + '_' + message.items.indexOf(item)"
            class="message-item-block"
          >
            <!-- 工具调用 -->
            <div v-if="item.type === 'toolCall'" class="tool-call-item">
              <div
                class="tool-call-header"
                @click="item.showArgs = !item.showArgs"
              >
                <el-icon class="tool-call-toggle-icon" :class="{ 'expanded': item.showArgs }">
                  <ArrowRight />
                </el-icon>
                <el-icon class="tool-icon">
                  <Tools />
                </el-icon>
                <span class="tool-name">{{ item.toolName }}</span>
                <el-tag
                  v-if="item.status === 'calling'"
                  size="small"
                  type="info"
                  class="tool-status"
                >
                  执行中
                </el-tag>
                <el-tag
                  v-else-if="item.status === 'completed'"
                  size="small"
                  type="success"
                  class="tool-status"
                >
                  完成
                </el-tag>
              </div>
              <!-- 参数详情（可折叠） -->
              <div v-show="item.showArgs && item.toolArgs" class="tool-call-details">
                <pre class="tool-call-code">{{ formatToolArgs(item.toolArgs) }}</pre>
              </div>
            </div>

            <!-- 文本块 -->
            <div v-else-if="item.type === 'text'" class="message-text">
              <div v-html="formatContent(item.content)"></div>
            </div>

            <!-- 趋势图 -->
            <div v-else-if="item.type === 'chart' && item.chartType === 'trend_chart'" class="chart-item">
              <TrendChart
                :timestamps="item.chartData?.timestamps || []"
                :values="item.chartData?.values || []"
                :data-points-count="item.chartData?.data_points_count || 0"
                :village-name="item.chartData?.village_name"
                :model-name="item.chartData?.model_name || item.chartData?.model_id"
                :model-id="item.chartData?.model_id"
              />
            </div>

            <!-- 知识库搜索结果 -->
            <div v-else-if="item.type === 'knowledge_search'" class="search-results-item">
              <SearchResultsContainer
                :data="item.searchData || {}"
                @view-detail="handleSearchResultDetail"
              />
            </div>

            <!-- 任务计划 -->
            <div v-else-if="item.type === 'plan'" class="plan-item">
              <PlanCard :plan-data="item.planData || {}" />
            </div>
          </div>
        </template>

        <!-- 兼容旧格式：如果没有 items，使用 content 和 toolCalls -->
        <template v-else>
          <!-- 工具调用列表 -->
          <div v-if="message.toolCalls && message.toolCalls.length > 0" class="tool-calls">
            <div
              v-for="toolCall in message.toolCalls"
              :key="toolCall.id"
              class="tool-call-item"
            >
              <div
                class="tool-call-header"
                @click="toolCall.showArgs = !toolCall.showArgs"
              >
                <el-icon class="tool-call-toggle-icon" :class="{ 'expanded': toolCall.showArgs }">
                  <ArrowRight />
                </el-icon>
                <el-icon class="tool-icon">
                  <Tools />
                </el-icon>
                <span class="tool-name">{{ toolCall.toolName }}</span>
                <el-tag
                  v-if="toolCall.status === 'calling'"
                  size="small"
                  type="info"
                  class="tool-status"
                >
                  执行中
                </el-tag>
                <el-tag
                  v-else-if="toolCall.status === 'completed'"
                  size="small"
                  type="success"
                  class="tool-status"
                >
                  完成
                </el-tag>
              </div>
              <!-- 参数详情（可折叠） -->
              <div v-show="toolCall.showArgs && toolCall.toolArgs" class="tool-call-details">
                <pre class="tool-call-code">{{ formatToolArgs(toolCall.toolArgs) }}</pre>
              </div>
            </div>
          </div>

          <div
            v-if="message.content"
            class="message-text"
            v-html="formatContent(message.content)"
          ></div>
        </template>

        <div v-if="message.status === 'streaming' && (!message.items || message.items.length === 0) && !message.content" class="message-typing">
          <span></span><span></span><span></span>
        </div>

        <div v-if="message.status === 'error'" class="message-error">
          <el-alert
            :title="message.error || '发生错误'"
            type="error"
            :closable="false"
            show-icon
          />
        </div>
      </div>

      <div class="message-time">
        {{ formatTime(message.timestamp) }}
        <el-tooltip 
          content="回滚到此处 (Time Travel)" 
          placement="top" 
          v-if="message.role === 'assistant' && message.checkpointId"
        >
          <el-button 
            link 
            type="primary" 
            size="small" 
            :icon="RefreshLeft"
            class="restore-btn"
            @click="$emit('restore')"
          >
            回滚
          </el-button>
        </el-tooltip>
      </div>
    </div>
  </div>
</template>

<script setup>
import { watch } from 'vue'
import { User, ChatDotRound, Tools, ArrowRight, RefreshLeft } from '@element-plus/icons-vue'
import { MESSAGE_STATUS } from '../utils/constants'
import { marked } from 'marked'
import TrendChart from './chatCard/TrendChart.vue'
import SearchResultsContainer from './chatCard/SearchResultsContainer.vue'
import PlanCard from './chatCard/PlanCard.vue'

const props = defineProps({
  message: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['restore'])

// 格式化内容（支持 Markdown 实时渲染）
const formatContent = (content) => {
  if (!content) return ''

  try {
    // 使用 marked 库渲染 markdown
    const html = marked(content, {
      breaks: true, // 支持换行
      gfm: true // 使用 GitHub Flavored Markdown
    })

    // 为代码块添加自定义样式类
    let formatted = html
      .replace(/<code>/g, '<code class="inline-code">')
      .replace(/<pre><code class="inline-code/g, '<pre><code')

    return formatted
  } catch (e) {
    console.error('Markdown parsing error:', e)
    // 降级处理：返回原始文本的转义版本
    let formatted = content
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
    formatted = formatted.replace(/\n/g, '<br>')
    return formatted
  }
}

// 格式化时间
const formatTime = (timestamp) => {
  const date = new Date(timestamp)
  const now = new Date()
  const diff = now - date

  if (diff < 60000) {
    return '刚刚'
  } else if (diff < 3600000) {
    return `${Math.floor(diff / 60000)}分钟前`
  } else if (diff < 86400000) {
    return `${Math.floor(diff / 3600000)}小时前`
  } else {
    return date.toLocaleString('zh-CN', {
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    })
  }
}

// 格式化工具参数
const formatToolArgs = (args) => {
  if (!args) return ''
  try {
    return JSON.stringify(args, null, 2)
  } catch (e) {
    return String(args)
  }
}

// 格式化工具参数预览（简洁版）
const formatToolArgsPreview = (args) => {
  if (!args) return ''
  try {
    const str = JSON.stringify(args)
    // 如果太长，截断
    if (str.length > 50) {
      return str.substring(0, 47) + '...'
    }
    return str
  } catch (e) {
    const str = String(args)
    if (str.length > 50) {
      return str.substring(0, 47) + '...'
    }
    return str
  }
}

// 初始化工具调用的折叠状态
watch(
  () => props.message.items,
  (items) => {
    if (items && Array.isArray(items)) {
      items.forEach(item => {
        if (item.type === 'toolCall' && item.showArgs === undefined) {
          item.showArgs = false
        }
      })
    }
  },
  { immediate: true, deep: true }
)

// 兼容旧格式
watch(
  () => props.message.toolCalls,
  (toolCalls) => {
    if (toolCalls && Array.isArray(toolCalls)) {
      toolCalls.forEach(toolCall => {
        // 默认折叠参数
        if (toolCall.showArgs === undefined) {
          toolCall.showArgs = false
        }
      })
    }
  },
  { immediate: true, deep: true }
)

// 处理知识库搜索结果详情
const handleSearchResultDetail = (result) => {
  // 可以在这里添加查看详情的逻辑，比如打开模态框
  console.log('查看知识库搜索结果详情:', result)
}
</script>

<style scoped>
.message-item {
  display: flex;
  margin-bottom: 1.5rem;
  animation: fadeIn 0.3s ease-in;
}

.message-user {
  flex-direction: row-reverse;
}

.message-assistant {
  flex-direction: row;
}

.message-avatar {
  flex-shrink: 0;
  margin: 0 0.75rem;
}

.message-content-wrapper {
  max-width: 70%;
  min-width: 0;
}

.message-user .message-content-wrapper {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.message-assistant .message-content-wrapper {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.message-content {
  padding: 0.75rem 1rem;
  border-radius: 0.75rem;
  word-wrap: break-word;
  word-break: break-word;
}

.message-user .message-content {
  background: var(--el-color-primary);
  color: #fff;
  border-bottom-right-radius: 0.25rem;
}

.message-assistant .message-content {
  background: var(--el-fill-color-blank);
  color: var(--el-text-color-primary);
  border: 1px solid var(--el-border-color-light);
  border-bottom-left-radius: 0.25rem;
}

.message-text {
  line-height: 1.6;
  word-wrap: break-word;
  word-break: break-word;
}

.message-text :deep(p) {
  margin: 0.5rem 0;
}

.message-text :deep(p:first-child) {
  margin-top: 0;
}

.message-text :deep(p:last-child) {
  margin-bottom: 0;
}

.message-text :deep(.inline-code) {
  background: var(--el-fill-color-light);
  padding: 0.125rem 0.375rem;
  border-radius: 0.25rem;
  font-family: 'Courier New', monospace;
  font-size: 0.9em;
}

.message-user .message-text :deep(.inline-code) {
  background: rgba(255, 255, 255, 0.25);
}

/* Markdown 代码块样式 */
.message-text :deep(pre) {
  background: var(--el-bg-color-page);
  border: 1px solid var(--el-border-color-light);
  border-radius: 0.375rem;
  padding: 0.75rem;
  overflow-x: auto;
  margin: 0.5rem 0;
  line-height: 1.4;
}

.message-text :deep(pre code) {
  color: #d4d4d4;
  font-family: 'Courier New', 'Consolas', monospace;
  font-size: 0.875rem;
  background: none;
  padding: 0;
}

/* Markdown 标题样式 */
.message-text :deep(h1) {
  font-size: 1.5rem;
  font-weight: 700;
  margin: 1rem 0 0.5rem 0;
}

.message-text :deep(h2) {
  font-size: 1.25rem;
  font-weight: 700;
  margin: 0.875rem 0 0.375rem 0;
}

.message-text :deep(h3) {
  font-size: 1.125rem;
  font-weight: 700;
  margin: 0.75rem 0 0.375rem 0;
}

.message-text :deep(h4),
.message-text :deep(h5),
.message-text :deep(h6) {
  font-weight: 700;
  margin: 0.5rem 0 0.375rem 0;
}

/* Markdown 列表样式 */
.message-text :deep(ul),
.message-text :deep(ol) {
  margin: 0.5rem 0;
  padding-left: 1.5rem;
}

.message-text :deep(li) {
  margin: 0.25rem 0;
}

/* Markdown 引用样式 */
.message-text :deep(blockquote) {
  margin: 0.5rem 0;
  padding-left: 1rem;
  border-left: 4px solid var(--el-color-primary);
  color: var(--el-text-color-secondary);
}

/* Markdown 表格样式 */
.message-text :deep(table) {
  border-collapse: collapse;
  width: 100%;
  margin: 0.5rem 0;
  font-size: 0.875rem;
}

.message-text :deep(table th),
.message-text :deep(table td) {
  border: 1px solid var(--el-border-color-light);
  padding: 0.5rem;
  text-align: left;
}

.message-text :deep(table th) {
  background: var(--el-fill-color-light);
  font-weight: 700;
}

/* Markdown 链接样式 */
.message-text :deep(a) {
  color: var(--el-color-primary);
  text-decoration: none;
}

.message-text :deep(a:hover) {
  text-decoration: underline;
}

.message-typing {
  display: flex;
  gap: 0.25rem;
  padding: 0.5rem 0;
}

.message-typing span {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: var(--el-text-color-placeholder);
  animation: typing 1.4s infinite;
}

.message-typing span:nth-child(2) {
  animation-delay: 0.2s;
}

.message-typing span:nth-child(3) {
  animation-delay: 0.4s;
}

.message-error {
  margin-top: 0.5rem;
}

.message-time {
  font-size: 0.75rem;
  color: var(--el-text-color-placeholder);
  margin-top: 0.25rem;
  padding: 0 0.25rem;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.restore-btn {
  opacity: 0;
  transition: opacity 0.2s;
  padding: 0;
  height: auto;
  font-size: 0.75rem;
}

.message-item:hover .restore-btn {
  opacity: 1;
}

/* 消息块容器 */
.message-item-block {
  margin-bottom: 0.5rem;
}

.message-item-block:last-child {
  margin-bottom: 0;
}

/* 工具调用样式 - Cursor 风格 */
.tool-calls {
  margin-bottom: 0.5rem;
}

.tool-call-item {
  margin-bottom: 0.375rem;
  padding: 0.375rem 0.5rem;
  background: var(--el-fill-color-light);
  border: 1px solid var(--el-border-color-light);
  border-radius: 0.375rem;
  font-size: 0.8125rem;
  transition: background-color 0.2s;
}

.tool-call-item:hover {
  background: var(--el-fill-color);
}

.tool-call-header {
  display: flex;
  align-items: center;
  gap: 0.375rem;
  cursor: pointer;
  user-select: none;
  line-height: 1.5;
}

.tool-call-toggle-icon {
  font-size: 0.75rem;
  transition: transform 0.2s;
  color: var(--el-text-color-secondary);
  flex-shrink: 0;
}

.tool-call-toggle-icon.expanded {
  transform: rotate(90deg);
}

.tool-icon {
  color: var(--el-color-primary);
  font-size: 0.875rem;
  flex-shrink: 0;
}

.tool-name {
  font-weight: 500;
  color: var(--el-text-color-primary);
  font-size: 0.8125rem;
}

.tool-call-args-preview {
  color: var(--el-text-color-secondary);
  font-size: 0.75rem;
  font-family: 'Courier New', 'Consolas', monospace;
  margin-left: 0.25rem;
}

.tool-status {
  margin-left: auto;
  flex-shrink: 0;
}

.tool-call-details {
  margin-top: 0.5rem;
  padding-top: 0.5rem;
  border-top: 1px solid var(--el-border-color-light);
}

.tool-call-code {
  background: var(--el-fill-color-blank);
  border: 1px solid var(--el-border-color-light);
  border-radius: 0.25rem;
  padding: 0.5rem;
  margin: 0;
  font-size: 0.75rem;
  font-family: 'Courier New', 'Consolas', monospace;
  color: var(--el-text-color-primary);
  overflow-x: auto;
  white-space: pre-wrap;
  word-break: break-word;
  max-height: 200px;
  overflow-y: auto;
  line-height: 1.4;
}

.message-assistant .tool-call-item {
  background: var(--el-color-primary-light-9);
  border-color: var(--el-color-primary-light-7);
}

@media (max-width: 768px) {
  .tool-call-item {
    padding: 0.375rem;
    font-size: 0.75rem;
  }

  .tool-call-code {
    font-size: 0.6875rem;
    padding: 0.375rem;
  }

  .tool-call-args-preview {
    display: none; /* 移动端隐藏预览 */
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
    opacity: 0.7;
  }
  30% {
    transform: translateY(-10px);
    opacity: 1;
  }
}

/* 趋势图样式 */
.chart-item {
  margin: 0.75rem 0;
  width: 100%;
  max-width: 100%;
}

.message-assistant .chart-item {
  padding: 0;
  background: transparent;
}

/* 知识库搜索结果样式 */
.search-results-item {
  margin: 0.75rem 0;
  width: 100%;
  max-width: 100%;
  border-radius: 0.5rem;
  overflow: hidden;
}

.message-assistant .search-results-item {
  padding: 0;
  background: transparent;
}

/* 任务计划样式 */
.plan-item {
  margin: 0.75rem 0;
  width: 100%;
  max-width: 100%;
}

.message-assistant .plan-item {
  padding: 0;
  background: transparent;
}

@media (max-width: 768px) {
  .message-content-wrapper {
    max-width: 85%;
  }

  .message-content {
    padding: 0.625rem 0.875rem;
    font-size: 0.9375rem;
  }

  .message-avatar {
    margin: 0 0.5rem;
  }

  .chart-item {
    margin: 0.5rem 0;
  }
}
</style>

